import { Injectable } from '@angular/core';

import { Http } from '@angular/http';
import { Service } from '../../server/server';
import { Subject } from 'rxjs';
import { Datatype } from '../institution/institution-table/institution-table.component';

@Injectable()
export class InstitutionService {

    //config: Config;
    private baseUrl: string = this.context.baseUrl;
    public InterfaceName: string = '';
    public tabVal: Datatype[] = [];
    public tabValSubject = new Subject<Datatype[]>();
    public reloadSubject = new Subject<string>();
    public disableInstitutionUrl = 'admin/institutions/modifyStatus';

    constructor(private http: Http, private context: Service) {
    }

    getParentInfos(data: any): Promise<Array<any>> {
        let url = 'admin/institutions/getParentInfos';
        return this.http
            .get(url)
            .toPromise()
            .then(res => {
                let r = res.json();
                //console.log(r);
                if (r.result_code !== '0000') {
                    throw new Error(r.message);
                } else {
                    //return Array<any>(r.result);
                    return this.processTreeData(r.result);
                }
            });
    }

    private processTreeData(list: Array<any>): Array<any> {
        return this.getTreeChildren(list, '0');
    }


    private getTreeChildren(list: Array<any>, parentId: string): Array<any> {
        let idKey: string = 'institutionId';
        let labelKey: string = 'institutionName';
        let result: Array<any> = [];
        for (let item of list) {
            if (item.parentId === parentId) {
                this.fillCSTreeNode(item, item[idKey], item[labelKey]);
                let children = this.getTreeChildren(list, item[idKey]);
                if (children && children.length > 0) {
                    item.children = children;
                    item.leaf = false;
                } else {
                    item.leaf = true;
                }
                result.push(item);
            }
        }
        return result;
    }

    private fillCSTreeNode(node: any, data: string, label: string): void {
        node.data = data;
        node.label = label;
        node.expandedIcon = 'fa-minus-square-o';
        node.collapsedIcon = 'fa-plus-square-o';
        node.expanded = false;
        //node.leaf = true;
        //node.icon = 'fa-dot-circle-o';
    }

    public enableInstitution(ids: string[], enabled: number) {
        return this.http.post(this.disableInstitutionUrl, {
            id: JSON.stringify(ids),
            enabled: enabled
        })
    }

    public selectedItems: string[] = [];
    public selectedItemsSubject = new Subject<Array<string>>();
    public isSeleted(val: string, arr?: Array<string>): string | boolean {
        arr = arr ? arr : this.selectedItems
        let isExist = arr.findIndex(each => each === val);
        if (isExist > -1) {
            return isExist + ''
        } else {
            return false
        }
    }
    public selectThis(val: string, arr: Array<string>): void {
        let key = this.isSeleted(val, arr)
        if (key) {
            arr.splice(+key, 1)
        } else {
            arr.push(val)
        }
    }
    public sendSelectedItems(val: string): void {
        this.selectThis(val, this.selectedItems);
        this.selectedItemsSubject.next(this.selectedItems)
    }
    public selectAll(tabVal: Array<any>) {
        if (this.selectedItems.length < tabVal.length) {
            this.selectedItems = [];
            tabVal.map(each => {
                this.selectedItems.push(each["institutionId"])
            })
        } else {
            this.selectedItems = []
        }
        this.selectedItemsSubject.next(this.selectedItems)
    }
    public clearSelectedItems() {
        this.selectedItems = [];
        this.selectedItemsSubject.next(this.selectedItems)
    }
}